import os
import gradio as gr
import dashscope
from datetime import datetime
import json
from pathlib import Path

# 配置dashscope
dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'

# 创建历史记录目录
HISTORY_DIR = Path("meeting_history")
HISTORY_DIR.mkdir(exist_ok=True)

def transcribe_audio(audio_file, language="auto"):
    """使用qwen3-asr-flash进行语音识别"""
    if audio_file is None:
        return None, "请上传音频文件"
    
    try:
        audio_path = f"file://{os.path.abspath(audio_file)}"
        
        messages = [
            {"role": "system", "content": [{"text": ""}]},
            {"role": "user", "content": [{"audio": audio_path}]}
        ]
        
        asr_options = {"enable_itn": True}
        if language != "auto":
            asr_options["language"] = language
        
        response = dashscope.MultiModalConversation.call(
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            model="qwen3-asr-flash",
            messages=messages,
            result_format="message",
            asr_options=asr_options
        )
        
        if response.status_code == 200:
            transcript = response.output.choices[0].message.content[0]["text"]
            word_count = len(transcript)
            return transcript, f"✓ 识别完成 | 字数: {word_count}"
        else:
            return None, f"识别失败: {response.message}"
            
    except Exception as e:
        return None, f"错误: {str(e)}"

def generate_summary(transcript, summary_type="standard"):
    """使用qwen-max生成会议总结"""
    if not transcript:
        return "请先完成语音识别"
    
    prompts = {
        "standard": "请提供专业的会议总结，包括：\n1. 会议主题\n2. 核心议题\n3. 关键决策\n4. 待办事项\n5. 后续跟进",
        "brief": "请用简洁的方式总结会议要点，突出最重要的3-5个关键信息",
        "detailed": "请提供详细的会议记录，包括：\n1. 会议背景\n2. 讨论过程\n3. 各方观点\n4. 决策依据\n5. 行动计划\n6. 时间节点",
        "action": "请专注于提取会议中的行动项，包括：\n1. 具体任务\n2. 责任人\n3. 截止时间\n4. 优先级"
    }
    
    try:
        messages = [
            {
                "role": "system",
                "content": "你是一位经验丰富的会议记录专员，擅长从会议内容中提炼关键信息。"
            },
            {
                "role": "user",
                "content": f"{prompts[summary_type]}\n\n会议内容：\n{transcript}"
            }
        ]
        
        response = dashscope.Generation.call(
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            model="qwen-max",
            messages=messages,
            result_format="message"
        )
        
        if response.status_code == 200:
            return response.output.choices[0].message.content
        else:
            return f"总结失败: {response.message}"
            
    except Exception as e:
        return f"错误: {str(e)}"

def extract_keywords(transcript):
    """提取关键词"""
    if not transcript:
        return "请先完成语音识别"
    
    try:
        messages = [
            {
                "role": "system",
                "content": "你是关键词提取专家。请从文本中提取5-10个最重要的关键词，用逗号分隔。"
            },
            {
                "role": "user",
                "content": transcript
            }
        ]
        
        response = dashscope.Generation.call(
            api_key=os.getenv("DASHSCOPE_API_KEY"),
            model="qwen-max",
            messages=messages,
            result_format="message"
        )
        
        if response.status_code == 200:
            return response.output.choices[0].message.content
        else:
            return "关键词提取失败"
            
    except Exception as e:
        return f"错误: {str(e)}"

def save_meeting_record(transcript, summary, keywords, meeting_title):
    """保存会议记录"""
    if not transcript:
        return "没有可保存的内容"
    
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    filename = f"meeting_{timestamp}.json"
    
    record = {
        "title": meeting_title or f"会议记录_{timestamp}",
        "timestamp": datetime.now().isoformat(),
        "transcript": transcript,
        "summary": summary,
        "keywords": keywords
    }
    
    filepath = HISTORY_DIR / filename
    with open(filepath, 'w', encoding='utf-8') as f:
        json.dump(record, f, ensure_ascii=False, indent=2)
    
    return f"✓ 已保存至: {filepath}"

def export_to_markdown(transcript, summary, keywords, meeting_title):
    """导出为Markdown格式"""
    if not transcript:
        return None, "没有可导出的内容"
    
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    title = meeting_title or f"会议记录_{datetime.now().strftime('%Y%m%d')}"
    
    markdown_content = f"""# {title}

**时间**: {timestamp}

## 关键词
{keywords}

---

## 会议总结
{summary}

---

## 完整记录
{transcript}

---
*本记录由会议助手自动生成*
"""
    
    filename = f"{title.replace(' ', '_')}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.md"
    filepath = HISTORY_DIR / filename
    
    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(markdown_content)
    
    return str(filepath), f"✓ 已导出至: {filepath}"

def process_meeting(audio_file, language, summary_type):
    """处理完整流程"""
    transcript, status = transcribe_audio(audio_file, language)
    
    if transcript is None:
        return status, "", "", ""
    
    summary = generate_summary(transcript, summary_type)
    keywords = extract_keywords(transcript)
    
    return status, transcript, summary, keywords

# 自定义CSS
custom_css = """
.container {
    max-width: 1400px;
    margin: auto;
}
.header {
    text-align: center;
    padding: 2rem 0;
    border-bottom: 2px solid #e5e7eb;
    margin-bottom: 2rem;
}
.header h1 {
    font-size: 2rem;
    font-weight: 600;
    color: #1f2937;
    margin-bottom: 0.5rem;
}
.header p {
    color: #6b7280;
    font-size: 1rem;
}
.section-title {
    font-size: 1.1rem;
    font-weight: 600;
    color: #374151;
    margin-bottom: 1rem;
    padding-bottom: 0.5rem;
    border-bottom: 1px solid #e5e7eb;
}
.status-box {
    padding: 0.75rem;
    border-radius: 0.5rem;
    background: #f3f4f6;
    font-size: 0.9rem;
    color: #374151;
}
"""

# 创建Gradio界面
with gr.Blocks(css=custom_css, title="会议助手") as demo:
    
    # 头部
    with gr.Row(elem_classes="header"):
        gr.HTML("""
            <div>
                <h1>会议助手</h1>
                <p>专业的会议记录与分析工具</p>
            </div>
        """)
    
    with gr.Row():
        # 左侧：输入区域
        with gr.Column(scale=2):
            gr.HTML('<div class="section-title">音频文件</div>')
            audio_input = gr.Audio(
                label="",
                type="filepath",
                sources=["upload"],
                show_label=False
            )
            
            with gr.Row():
                language_select = gr.Dropdown(
                    choices=[
                        ("自动检测", "auto"),
                        ("中文", "zh"),
                        ("英文", "en"),
                        ("日语", "ja"),
                        ("韩语", "ko")
                    ],
                    value="auto",
                    label="语言",
                    scale=1
                )
                
                summary_type = gr.Dropdown(
                    choices=[
                        ("标准总结", "standard"),
                        ("简要总结", "brief"),
                        ("详细记录", "detailed"),
                        ("行动清单", "action")
                    ],
                    value="standard",
                    label="总结类型",
                    scale=1
                )
            
            process_btn = gr.Button("开始处理", variant="primary", size="lg")
            
            status_output = gr.Textbox(
                label="处理状态",
                interactive=False,
                show_label=True
            )
        
        # 右侧：输出区域
        with gr.Column(scale=3):
            with gr.Tabs():
                with gr.Tab("总结"):
                    summary_output = gr.Textbox(
                        label="",
                        lines=15,
                        show_label=False,
                        placeholder="会议总结将在这里显示..."
                    )
                
                with gr.Tab("完整记录"):
                    transcript_output = gr.Textbox(
                        label="",
                        lines=15,
                        show_label=False,
                        placeholder="完整的语音识别文本将在这里显示..."
                    )
                
                with gr.Tab("关键词"):
                    keywords_output = gr.Textbox(
                        label="",
                        lines=15,
                        show_label=False,
                        placeholder="关键词将在这里显示..."
                    )
    
    # 底部：操作区域
    with gr.Row():
        with gr.Column(scale=3):
            meeting_title_input = gr.Textbox(
                label="会议标题（可选）",
                placeholder="例如：2024年Q1产品规划会议"
            )
        
        with gr.Column(scale=1):
            save_btn = gr.Button("保存记录", size="lg")
            export_btn = gr.Button("导出Markdown", size="lg")
    
    with gr.Row():
        save_status = gr.Textbox(label="保存状态", interactive=False)
        export_status = gr.Textbox(label="导出状态", interactive=False)
    
    # 事件绑定
    process_btn.click(
        fn=process_meeting,
        inputs=[audio_input, language_select, summary_type],
        outputs=[status_output, transcript_output, summary_output, keywords_output]
    )
    
    save_btn.click(
        fn=save_meeting_record,
        inputs=[transcript_output, summary_output, keywords_output, meeting_title_input],
        outputs=[save_status]
    )
    
    export_btn.click(
        fn=export_to_markdown,
        inputs=[transcript_output, summary_output, keywords_output, meeting_title_input],
        outputs=[gr.File(label="下载文件"), export_status]
    )

if __name__ == "__main__":
    demo.launch(share=False, server_name="127.0.0.1", server_port=7860)
